package com.cskaoyan.service.wx;

import com.cskaoyan.bean.MarketRegister;
import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.MarketUserExample;
import com.cskaoyan.config.AliyunComponent;
import com.cskaoyan.mapper.MarketRegisterMapper;
import com.cskaoyan.mapper.MarketUserMapper;
import com.cskaoyan.model.vx.bo.WxRegisterBo;
import com.cskaoyan.model.vx.vo.WxLoginBaseDataVo;
import com.cskaoyan.model.vx.vo.WxLoginDataVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeoutException;

/**
 * @author hanshuai
 * @version 1.0
 * @description @TODO
 * @date 2021/12/3 20:04
 */
@Service
public class WxAuthServiceImpl implements WxAuthService {
    @Autowired
    MarketUserMapper marketUserMapper;

    @Autowired
    AliyunComponent aliyunComponent;
    @Autowired
    MarketRegisterMapper marketRegisterMapper;

    @Override
    public WxLoginDataVo wxLogin(String username, String password) {
        WxLoginDataVo wxLoginDataVo = new WxLoginDataVo();
        MarketUserExample example = new MarketUserExample();
        example.createCriteria().andUsernameEqualTo(username).andPasswordEqualTo(password);
        List<MarketUser> marketUsers = marketUserMapper.selectByExample(example);
        if (marketUsers == null) {
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute("wxUserId", marketUsers.get(0).getId());

        marketUsers.get(0).setLastLoginIp(subject.getSession().getHost());
        marketUsers.get(0).setLastLoginTime(new Date());
        marketUsers.get(0).setSessionKey((String) subject.getSession().getId());
        wxLoginDataVo.setToken((String) subject.getSession().getId());
        WxLoginBaseDataVo wxLoginBaseDataVo = new WxLoginBaseDataVo();
        wxLoginBaseDataVo.setNickName(marketUsers.get(0).getNickname());
        wxLoginBaseDataVo.setAvatarUrl(marketUsers.get(0).getAvatar());
        wxLoginDataVo.setUserInfo(wxLoginBaseDataVo);
        wxLoginDataVo.setToken((String) subject.getSession().getId());
        return wxLoginDataVo;
    }

    @Override
    public void wxLogout(HttpSession httpSession) {
        httpSession.invalidate();
    }


    @Override
    public void wxAuthRegCaptcha(String mobile, HttpSession httpSession) {
        MarketRegister marketRegister = marketRegisterMapper.selectMarketRegisterByMobile(mobile);
        if (marketRegister == null) {
            marketRegisterMapper.insertRegister(mobile);
        }
//        Long captCharTime = (Long) httpSession.getAttribute("captCharTime");
        //如果存在session 时间戳 并且没有超过1分钟，就不让再发送
        if (marketRegister != null && (marketRegister.getCaptChar() != null && System.currentTimeMillis() - marketRegister.getCaptChar() <= 1000 * 60 * 1)) {
            throw new IllegalArgumentException();
        }
        String code = String.valueOf((int) (Math.random() * 999 + 1000));
        aliyunComponent.sendMsg(mobile, code);
        //每次发送把code 和时间记录到 session
//        Subject subject = SecurityUtils.getSubject();
//        subject.getSession().setAttribute("code", code);
//        subject.getSession().setAttribute("captCharTime", System.currentTimeMillis());
        marketRegisterMapper.updateMarketRegister(mobile, code, System.currentTimeMillis());
//        httpSession.setAttribute("code", code);
//        httpSession.setAttribute("captCharTime", System.currentTimeMillis());

    }

    @Override
    public Integer wxRegister(WxRegisterBo wxRegisterBo) {
        MarketUserExample example = new MarketUserExample();
        example.createCriteria().andUsernameEqualTo(wxRegisterBo.getUsername());
        List<MarketUser> marketUsers = marketUserMapper.selectByExample(example);
        if (marketUsers.size() != 0) {
            //1 表示 用户名已存在
            return 1;
        }
        example.createCriteria().andMobileEqualTo(wxRegisterBo.getMobile());
        List<MarketUser> marketUsers1 = marketUserMapper.selectByExample(example);
        if (marketUsers1.size() != 0) {
            //2 表示 手机号已存在
            return 2;
        }
        MarketRegister marketRegister = marketRegisterMapper.selectMarketRegisterByMobile(wxRegisterBo.getMobile());
        if (!marketRegister.getCode().equals(wxRegisterBo.getCode())) {
            // 3 表示 验证码错误
            return 3;
        }
        if (wxRegisterBo.getMobile().length() != 11) {
            // 4 表示 手机号参数错误
            return 4;
        }
        MarketUser marketUser = new MarketUser();
        marketUser.setAddTime(new Date());
        marketUser.setMobile(wxRegisterBo.getMobile());
        marketUser.setPassword(wxRegisterBo.getPassword());
        marketUser.setMobile(wxRegisterBo.getMobile());
        marketUser.setDeleted(false);
        marketUser.setUsername(wxRegisterBo.getUsername());
        marketUser.setWeixinOpenid(wxRegisterBo.getWxCode());
        marketUserMapper.insertSelective(marketUser);

        //成功返回 0
        return 0;
    }

    @Override
    public Integer wxReset(String code, String mobile, String password) {
        MarketUserExample example = new MarketUserExample();
        example.createCriteria().andMobileEqualTo(mobile);
        List<MarketUser> marketUsers = marketUserMapper.selectByExample(example);
        if (marketUsers.size() == 0) {
            //1 表示手机号尚未注册
            return 1;
        }
        MarketRegister marketRegister = marketRegisterMapper.selectMarketRegisterByMobile(mobile);
        if (!marketRegister.getMobile().equals(code)) {
            //2 表示 验证码错误
            return 2;
        }
        if (password.length() < 6) {
            // 3表示密码长度过短
            return 3;
        }
        marketUsers.get(0).setPassword(password);
        marketUserMapper.updateByExampleSelective(marketUsers.get(0), example);
        //0 表示 ok
        return 0;
    }
}
